//
//  ConfirmOrderController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/20.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "CarConfirmOrderController.h"
#import "ConfirmOrderController.h"
#import "ConfirmView.h"
#import "ShopSecondCell.h"
#import "ConfirmOrderCell.h"

#import "AddressManagerController.h"
#import "OrderPaymentController.h"
#import "ProductInfo.h"
#import "AddressModel.h"
#import "AddressTableViewCell.h"
#import "DefaultAddressModel.h"

#import "GoodsOrderDetailsFirstCell.h"

@interface ConfirmOrderController ()<UITableViewDelegate,UITableViewDataSource,ConfirmViewOrderDelagate,ThreeViewControllerDelegate>

{
    NSInteger index;
    AddressModel *address;
    BOOL  judgeAddress;
    NSMutableArray *allProductArray;
    DefaultAddressModel *defaultAddress;
    MBProgressHUD *progressHUD;
    
    
    NSString *_name;
    NSString *_phone;
    NSString *_province;
    NSString *_city;
    NSString *_county;
    NSString *_address;
    NSString *_postcode;
}

@property(nonatomic,strong)UITableView *confirmOrderView;

@property (nonatomic,strong)ConfirmView *lastView;

@property (nonatomic,strong)NSMutableArray *standardArr;
@property(nonatomic,strong)NSMutableDictionary *standtitleDict;

@end

@implementation ConfirmOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"确认订单";
    [self addUI];
    
    if (!address) {
        [self getTacitlyAddressData];
    }
    
    //    NSLog(@"-------------%@",_pruductDict);
    NSLog(@"%@",self.limitString);
}


- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSLog(@"%s",__func__);
    defaultAddress = nil;
    NSLog(@"%@",defaultAddress);
}

- (void)dealloc {
    [progressHUD removeFromSuperViewOnHide];
}

- (void)addUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UITableView *confirmOrderView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,WIDTH, HEIGHT * 0.8) style:UITableViewStyleGrouped];
    self.confirmOrderView = confirmOrderView;
    [self.view addSubview:confirmOrderView];
    confirmOrderView.delegate = self;
    confirmOrderView.dataSource = self;
    
    ConfirmView *lastView = [[ConfirmView alloc] initWithFrame:CGRectMake(0,HEIGHT * 0.8,WIDTH,HEIGHT/9)];
    lastView.delegate = self;
    //价格+邮费
    NSString *price= [NSString stringWithFormat:@"¥%zd",[self.allPrice integerValue] + [self.pruductDict[@"jzh"] integerValue]];
    lastView.totalPrice.text = [NSString stringWithFormat:@"总价:%@",price];
    [self.view addSubview:lastView];
}


#pragma mark 确认下单
- (void)confirmViewOrderDidClick:(UIButton *)button
{
    
    
    if(!(address || defaultAddress)) {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请选择正确地址" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        return;
    }else{
        
        progressHUD = [MBProgressHUD show:self.view andMessage:@"正在创建订单"];
        [self.view addSubview:progressHUD];
    }
    
    
    
    if (address) {
        _name = address.name;
        _phone = address.phone;
        _province = address.province;
        _city = address.city;
        _county = address.county;
        _address = address.address;
        _postcode = address.postcode;
    }
    
    if (defaultAddress) {
        _name = defaultAddress.name;
        _phone = defaultAddress.phone;
        _province = defaultAddress.province;
        _city = defaultAddress.city;
        _county = defaultAddress.county;
        _address = defaultAddress.address;
        _postcode = defaultAddress.postcode;
    }
    
#warning  点击立即购买商品 将商品先加入购物车创建购物车id 然后根据购物车id 创建商品订单
    NSDictionary *param;
    if (_judgeStandard) {
        
        param = @{@"pid":_pruductDict[@"pid"],
                  @"username":USERNAME,
                  @"num":@"1",
                  @"sn":_pruductDict[@"sn"]
                  };
        
        
    }else{
        
        param = @{@"pid":_pruductDict[@"pid"],
                  @"username":[NSString stringWithFormat:@"%@",USERNAME],
                  @"chima":_pruductDict[@"尺码"],
                  @"yanse":_pruductDict[@"颜色"],
                  @"kouwei":_pruductDict[@"口味"],
                  @"taocan":_pruductDict[@"套餐"],
                  @"xinghao":_pruductDict[@"型号"],
                  @"guige":_pruductDict[@"规格"],
                  @"num":_pruductDict[@"num"],
                  @"yscontent":_pruductDict[@"样式"],
                  @"sn":_pruductDict[@"sn"]
                  };
        
    }
    
    NSLog(@"%@",param);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:param AndMenthodName:@"/api/Cart/add" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            NSDictionary *dict = [object objectForKey:@"data"];
            [self CreateGoodsOrderNumberData:[dict objectForKey:@"cart_id"]];
            
        }
    }];
    
}

//根据cart_id创建商品订单
- (void)CreateGoodsOrderNumberData:(NSString *)cart_id
{
    
    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"business_type":@"shop",
                             @"cart_id":cart_id,
                             @"good_num":_pruductDict[@"num"],
                             @"name":_name,
                             @"phone":_phone,
                             @"province":_province,
                             @"city":_city,
                             @"county":_county,
                             @"address":_address,
                             @"postcode":_postcode
                             };
    
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/createOrderId" completeBlock:^(id object) {
        NSLog(@"-----%@",object);
        
        [progressHUD hide:YES];
        if(JudgeBackDataCode) {
            
            OrderPaymentController *OrderPaymentVC = [[OrderPaymentController alloc] init];
            
            NSDictionary *dict = [object objectForKey:@"data"];
            OrderPaymentVC.OrderString = dict[@"oid"];
            OrderPaymentVC.OrderMonryString = dict[@"totalmoney"];
            OrderPaymentVC.OrderTitleString = @"商城订单";
            OrderPaymentVC.orderType = @"3";
            
            NSString *string = [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",self.limitString]];
            
            if ([string isEqualToString:@"1"]) {
                OrderPaymentVC.judgeString = [NSString stringWithFormat:@"%@",self.limitString];
            }
            
            OrderPaymentVC.OrderDescribeInfo = [NSString stringWithFormat:@"商城订单%@",dict[@"totalmoney"]];
            
            [self.navigationController pushForm:self.navigationController pushToAndHidden:OrderPaymentVC];
            
        } else if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqualToString:@"-9000"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSDictionary *MessageDict = [object objectForKey:@"message"];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:MessageDict[@"view"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    MyAccountTableViewController *accountVC = [[MyAccountTableViewController alloc] init];
                    [self.navigationController pushForm:self.navigationController pushToAndHidden:accountVC];
                }];
                [alert addAction:SettingAction];
                
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:cancelAction];
                
                [self presentViewController:alert animated:YES completion:nil];
                
            });
        } else{
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:[object objectForKey:@"message"][@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
            
        }
        
    }];
}



- (void)getTacitlyAddressData {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"username":USERNAME} AndMenthodName:@"/api/User/addresDefault" completeBlock:^(id object) {
            if (JudgeBackDataCode) {
                NSDictionary *Default = [object objectForKey:@"data"];
                if (Default) {
                    defaultAddress = [[DefaultAddressModel alloc] initWithDictionary:Default error:nil];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.confirmOrderView reloadData];
                    });
                }
            }
        }];
    });
}

#pragma mark>>>>>>>>DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else{
        return 3;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {
        
        if (address || defaultAddress) {
            
            static NSString *identifier= @"ConfirmOrderControllerCell";
            GoodsOrderDetailsFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell==nil) {
                
                cell = [[GoodsOrderDetailsFirstCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            cell.NameLabel.text = [NSString stringWithFormat:@"收货人: %@    %@",address.name,address.phone];
            cell.AddressLabel.text = [NSString stringWithFormat:@"详细地址: %@%@%@%@",address.province,address.city,address.county,address.address];
            
            if (defaultAddress) {
                cell.NameLabel.text = [NSString stringWithFormat:@"收货人: %@    %@",defaultAddress.name,defaultAddress.phone];
                
                cell.AddressLabel.text = [NSString stringWithFormat:@"详细地址: %@%@%@%@",defaultAddress.province,defaultAddress.city,defaultAddress.county,defaultAddress.address];
            }
            
            return cell;
            
        } else {
            
            UITableViewCell *firstCell=[tableView dequeueReusableCellWithIdentifier:@"first"];
            
            if (firstCell==nil) {
                firstCell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"first"];
                firstCell.selectionStyle = UITableViewCellSelectionStyleNone;
                firstCell.textLabel.font = FONT(15);
                firstCell.detailTextLabel.font = FONT(15);
            }
            
            
            firstCell.textLabel.text = @"请填写收货地址";
            firstCell.imageView.image = [UIImage imageNamed:@"confirmOrder"];
            firstCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return firstCell;
        }
        
    }else {
        
        if (indexPath.row == 0) {
            
            ConfirmOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConfirmOrder"];
            if (cell == nil) {
                cell = [[ConfirmOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ConfirmOrder"];
                
                //规格
                cell.orderColorSize.text = [self goodsStandardStr];
            }
            
            //图片
            NSDictionary *tempDict = _pruductDict[@"picprex"];
            NSString *string = [NSString stringWithFormat:@"%@%@",tempDict[@"m"],_pruductDict[@"picurl"]];
            [cell.orderImg sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"goodsLoadJGG.jpg"]];
            cell.orderImg.contentMode = UIViewContentModeScaleToFill;
            
            cell.orderName.text = _pruductDict[@"title"];
            cell.orderNumber.text = [NSString stringWithFormat:@"x%@",_pruductDict[@"num"]];
            cell.orderPrice.text = [NSString stringWithFormat:@"¥%@",_pruductDict[@"huiyuanjia"]];
            
            
            
            return cell;
            
        }else{
            
            static NSString *identifier= @"ConfirmOrderCell";
            
            UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
            
            if (cell==nil) {
                cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.font = FONT(15);
                cell.detailTextLabel.font = FONT(15);
            }
            
            
            
            NSArray *arr1 = @[@"配送方式 :",@"价格总计 :"];
            //价格+邮费
            NSString *price= [NSString stringWithFormat:@"¥%zd",[self.allPrice integerValue] + [self.pruductDict[@"jzh"] integerValue]];
            
            NSArray *arr2 = @[[NSString stringWithFormat:@"快递¥%@",self.pruductDict[@"jzh"]],price];
            //包邮
            if ([self.pruductDict[@"jzh"] integerValue] == 0) {
                arr2 = @[@"包邮",price];
            }
            
            cell.textLabel.text = arr1[indexPath.row -1];
            cell.detailTextLabel.text = arr2[indexPath.row -1];
            
            return cell;
        }
        
    }
    
    
}



#pragma mark>>>>>>>>Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        AddressManagerController *AddressManagerVC = [[AddressManagerController alloc] init];
        AddressManagerVC.delegate = self;
        //        AddressManagerVC.productArray = self.productArray;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:AddressManagerVC];
    }
}

- (void)addViewController:(AddressManagerController *)addViewContrioller addUser:(AddressModel *)userDict andProductArray:(NSMutableArray *)productArray {
    address = userDict;
    NSLog(@"%@",address);
    
    [self.confirmOrderView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0) {
        return HEIGHT/10;
    }else if(indexPath.section == 1 && indexPath.row == 0 ){
        
        if (iPhone5) {
            return HEIGHT/6;
        }else if (iPhone6){
            return HEIGHT/7;
        }else{
            return HEIGHT/7;
        }
    }else{
        return HEIGHT/13;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (NSMutableArray *)standardArr {
    if (!_standardArr) {
        _standardArr = [NSMutableArray array];
    }
    return _standardArr;
}

- (NSMutableDictionary *)standtitleDict
{
    if (!_standtitleDict) {
        _standtitleDict = [NSMutableDictionary dictionary];
    }
    return _standtitleDict;
}


//返回规格
- (NSString *)goodsStandardStr
{
    
    //无规格 返回空字符串
    if (_judgeStandard) {
        return @"";
    }
    
    if (![_pruductDict[@"尺码"] isEqualToString:@"(null)"]) {
        [self.standardArr addObject:_pruductDict[@"尺码"]];
        [self.standtitleDict setObject:@"尺码" forKey:_pruductDict[@"尺码"]];
    }
    if (![_pruductDict[@"颜色"] isEqualToString:@"(null)"]) {
        [self.standardArr addObject:_pruductDict[@"颜色"]];
        [self.standtitleDict setObject:@"颜色" forKey:_pruductDict[@"颜色"]];
    }
    if (![_pruductDict[@"套餐"] isEqualToString:@"(null)"]) {
        [self.standardArr addObject:_pruductDict[@"套餐"]];
        [self.standtitleDict setObject:@"套餐" forKey:_pruductDict[@"套餐"]];
    }
    if (![_pruductDict[@"口味"] isEqualToString:@"(null)"]) {
        [self.standardArr addObject:_pruductDict[@"口味"]];
        [self.standtitleDict setObject:@"口味" forKey:_pruductDict[@"口味"]];
    }
    if (![_pruductDict[@"规格"] isEqualToString:@"(null)"]) {
        [self.standardArr addObject:_pruductDict[@"规格"]];
        [self.standtitleDict setObject:@"规格" forKey:_pruductDict[@"规格"]];
    }
    if (![_pruductDict[@"型号"] isEqualToString:@"(null)"]) {
        [self.standardArr addObject:_pruductDict[@"型号"]];
        [self.standtitleDict setObject:@"型号" forKey:_pruductDict[@"型号"]];
    }
    
    if ([self.ysSelectName length] > 0) {
        NSEnumerator * key = [_pruductDict keyEnumerator];
        for (NSObject *object in key) {
            //            NSLog(@"* * * *%@",object);
            
            if (![self.ysSelectName isEqualToString:[NSString stringWithFormat:@"%@",object]]) {
                
                if (!_judgeYsName) {
                    [self.standardArr addObject:_pruductDict[self.ysSelectName]];
                    [self.standtitleDict setObject:self.ysSelectName forKey:_pruductDict[self.ysSelectName]];
                }
                break;
            }
            
        }
        
    }
    
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.standardArr.count; ++i) {
        NSString *tempStr = [self.standtitleDict objectForKey:self.standardArr[i]];
        NSString *StandardStr = [NSString stringWithFormat:@"%@:%@ ",tempStr,self.standardArr[i]];
        [arr addObject:StandardStr];
    }
    
    NSMutableString * string = [[NSMutableString alloc] init];
    for (NSString *str in arr) {
        [string appendString:str];
    }
    
    return string;
    
}


@end
